package com.whh.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseUtils {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {
        Properties properties = new Properties();
        InputStream is = BaseUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //获取链接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,username,password);
    }
    //编写查询公共类
    public static ResultSet execute(Connection connection,PreparedStatement pstm,ResultSet resultSet,String sql,Object[] params) throws SQLException {
         pstm=connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            pstm.setObject(i+1,params[i]);
        }
        resultSet=pstm.executeQuery();
        return resultSet;
    }
    //编写增删改公共类
    public static int execute(Connection connection,PreparedStatement pstm ,String sql,Object[] params) throws SQLException {
         pstm=connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            pstm.setObject(i+1,params[i]);
        }
        int updateRows=pstm.executeUpdate();
        return updateRows;
    }

    //释放资源
    public static boolean closeResource(Connection conn, PreparedStatement pst, ResultSet rs) {
        boolean flag=true;
        if (rs != null) {
            try {
                rs.close();
                rs=null;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                flag=false;
            }
        }

        if (pst != null) {
            try {
                pst.close();
                pst=null;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                flag=false;
            }
        }


        if (conn != null) {
            try {
                conn.close();
                conn=null;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                flag=false;
            }
        }
        return flag;
    }
}
